// 同步连接
// @author 风杨
// @date 22-9-27 下午2:25
// @see <a href="yueny09@163.com">mailTo: yueny09@163.com</a>
//
use std::io::Error;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
use std::sync::{Arc, Mutex};
use std::thread;

use redis::{Commands, Connection, Client, RedisError, RedisResult, ConnectionLike};
// use redis::JsonCommands;
use redis::ToRedisArgs;

use log::info;

use crate::config::{get_value};
use crate::init_config;
use crate::r#const::{KEY_REDIS_HOSTNAME, KEY_REDIS_PASSWORD, KEY_REDIS_PORT, KEY_REDIS_USER_NAME};


/// 同步连接demo
/// param address:   let address = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 6379));
pub fn redis_demo_sync() -> Connection {
    // 建立连接
    // connect to redis
    // The URL format is redis://[<username>][:<password>@]<hostname>[:port][/<db>]
    let redisUrl = "redis://".to_owned()
        + &*get_value(KEY_REDIS_USER_NAME)
        + ":"
        + &*get_value(KEY_REDIS_PASSWORD)
        + "@"
        + &*get_value(KEY_REDIS_HOSTNAME)
        + ":"
        + &*get_value(KEY_REDIS_PORT);

    let client: Client = redis::Client::open(redisUrl)
        .unwrap();

    client.get_connection().unwrap()
}


#[test]
fn test() {
    init_config();

    let mut conn = redis_demo_sync();
    assert!(conn.is_open());

    let _ : () = conn.set("my_key", 33).unwrap();
    // read back the key and return it.  Because the return value
    // from the function is a result for integer this will automatically
    // convert into one.
    let val = conn.get::<String, String>("my_key".parse().unwrap());
    assert_eq!(val.unwrap(), "33");

    let delRs: u16 = conn.del::<&str, u16>("my_key").unwrap();
    assert_eq!(delRs, 1);

    let val = conn.get::<String, String>("my_key".parse().unwrap());
    // 数据不存在， 所以查询会报错, isErr = true
    let isErr = val.is_err();
    assert!(isErr);
}
